/*******************************************************************************
 * @project: aohuproject
 * @package: com.aohua.px
 * @file: NumberAutoGenerateAction.java
 * @author: fionn
 * @created: 2015年8月13日
 * @purpose:
 * 
 * @version: 1.0
 * 
 * 
 * Copyright 2015 HAND All rights reserved.
 ******************************************************************************/
package com.aohua.px;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.agile.api.APIException;
import com.agile.api.IAgileSession;
import com.agile.api.ICell;
import com.agile.api.IDataObject;
import com.agile.api.IItem;
import com.agile.api.INode;
import com.agile.api.ItemConstants;
import com.agile.px.ActionResult;
import com.agile.px.EventActionResult;
import com.agile.px.ICreateEventInfo;
import com.agile.px.IEventAction;
import com.agile.px.IEventInfo;
import com.hand.agile.utils.CellUtils;
import com.hand.config.A9ListConfig;
import com.hand.config.SystemConfigAdaptor;

/**
 * @author fionn
 *
 */
public class NumberAutoGenerateAction implements IEventAction {

    private static Logger log = Logger.getLogger(NumberAutoGenerateAction.class);
    private Properties config;
    private String hyphen;
    /**
     * 
     */
    public NumberAutoGenerateAction() {
        
    }
    
    /* (non-Javadoc)
     * @see com.agile.px.IEventAction#doAction(com.agile.api.IAgileSession, com.agile.api.INode, com.agile.px.IEventInfo)
     */
    @Override
    public EventActionResult doAction(IAgileSession session, INode arg1,
            IEventInfo arg2) {
        // save event
        EventActionResult result = null;
        try {
            session.disableAllWarnings();
            String[] path = {"物料编码"};
            Map<String, A9ListConfig> configs = SystemConfigAdaptor.getCaseConfigs(session.getAdminInstance(), path);
            ICreateEventInfo eventInfo = (ICreateEventInfo)arg2;
            result = new EventActionResult(eventInfo,doAction(session, eventInfo, configs));
        } catch (Exception e) {
            result = new EventActionResult(arg2, new ActionResult(ActionResult.EXCEPTION, e));
            log.error(e);
            e.printStackTrace(System.out);
        } finally {
            try {
                session.enableAllWarnings();
            } catch (APIException e) {
                log.error(e);
            }
        }
        return result;
    }

    /* (non-Javadoc)
     * @see com.agile.px.ICustomAction#doAction(com.agile.api.IAgileSession, com.agile.api.INode, com.agile.api.IDataObject)
     */
    public ActionResult doAction2(IAgileSession session, INode arg1,
            IDataObject arg2) {
        ActionResult result = null;
        try {
            session.disableAllWarnings();
            IItem item = (IItem)arg2;
            generateNumber(item);
            result = new ActionResult(ActionResult.STRING, "自动编码成功.");
        } catch (Exception e) {
            result = new ActionResult(ActionResult.EXCEPTION, e);
            log.error(e);
            e.printStackTrace(System.out);
        } finally {
            try {
                session.enableAllWarnings();
            } catch (APIException e) {
                log.error(e);
            }
        }
        return result;
    }
    
    public ActionResult doAction(IAgileSession session, ICreateEventInfo eventinfo, Map<String, A9ListConfig> configs) throws APIException {
        Object obj = eventinfo.getValue(ItemConstants.ATT_TITLE_BLOCK_DESCRIPTION);
        if(obj == null) return new ActionResult(ActionResult.EXCEPTION, new Exception("物料描述为空, 编码生成出错."));
        String description = String.valueOf(obj);
        String tmpNumber = (String)eventinfo.getNewNumber();//eventinfo.getValue(ItemConstants.ATT_TITLE_BLOCK_NUMBER);
        String number = getNumber(tmpNumber, description, configs);
        if(number.equals(""))  return new ActionResult(ActionResult.EXCEPTION, "描述不符合规则, 取消自动编码.");
        eventinfo.setNewNumber(number);
        return new ActionResult(ActionResult.STRING, "自动编码成功.");
    }

    private String getNumber(String tmpNumber, String description, Map<String, A9ListConfig> configs) {
        A9ListConfig rexconfig = configs.get("文本规则");
        A9ListConfig filterconfig = configs.get("过滤字符");
//        String rex = "([\\d+\\.\\*x×∮Φφ]+)";
//        String filter = "[∮Φφ]"
        String rex = rexconfig.getValue();
        Pattern pattern = Pattern.compile(rex);
        Matcher matcher = pattern.matcher(description);
        String number = matcher.find() ? matcher.group(0).replaceAll(filterconfig.getValue(), "") : "";
        return tmpNumber.substring(0,tmpNumber.length()-5) + number;
    }
    
    private void generateNumber(IItem item) throws APIException {
        initConfig();
        ICell cell = item.getCell(config.getProperty("attributeFlaged"));
        String type = CellUtils.getCellStringValue(cell);
        String attrstr = config.getProperty(type);
        if(attrstr == null || "".equals(attrstr)) {
            throw new APIException(new Exception(type + " 未配置自动编码规则。"));
        }
        StringBuilder sb = new StringBuilder();
        String[] apis = attrstr.split(",");
        for(int i = 0; i<(apis.length -1) ; i++) {
            cell = item.getCell(apis[i]);
            sb.append(CellUtils.getCellStringValue(cell)).append(hyphen);
        }
        sb.append(CellUtils.getCellStringValue(item.getCell(apis[apis.length - 1])));
        item.setValue(ItemConstants.ATT_TITLE_BLOCK_NUMBER, sb.toString());
    }
 
    private void initConfig() {
        InputStream in = null;
        try {
            in = NumberAutoGenerateAction.class.getClassLoader().getResourceAsStream("/autonumber.xml");
            config = new Properties();
            config.loadFromXML(in);
            this.hyphen = config.getProperty("hyphen");
        } catch (Exception e) {
            log.error(e);
            e.printStackTrace(System.out);
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    }
}
